from django.views.generic import View
from ..models import CaseModel
from ..forms import CaseForm
from ..constant import Method, Protocol, DataType, AssertType, AssertRelation
from utils.messages import Json_Response, Form_Invalid
from utils.decorators import permission_verify
from utils.paginate import paginate
from utils.record import record
from copy import deepcopy
import time


class CaseView(View):

    def info(self, request):
        result = {}
        result.setdefault('method', [{'key': k, 'value': v} for k, v in Method.value])
        result.setdefault('protocol', [{'key': k, 'value': v} for k, v in Protocol.value])
        result.setdefault('data_type', [{'key': k, 'value': v} for k, v in DataType.value])
        result.setdefault('assert_type', [{'key': k, 'value': v} for k, v in AssertType.value])
        result.setdefault('assert_relation', [{'key': k, 'value': v} for k, v in AssertRelation.value])

        return Json_Response(msg='查询成功', data=result)

    def _create_case(self, case_dict):
        if not CaseModel.objects.filter(name=case_dict['name']):
            obj = CaseModel.objects.create(**case_dict)
            return obj

    @permission_verify(40002)
    def create(self, request):
        form = CaseForm.Create(request)
        if form.is_valid():
            data = form.cleaned_data
            obj = self._create_case(data)
            if obj:
                record(request, 11, obj)
                return Json_Response(msg='创建成功')
            else:
                return Json_Response(code=201, err_msg='用例已存在')
        else:
            return Form_Invalid(form)

    @permission_verify(40002)
    def update(self, request):
        form = CaseForm.Update(request)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            qs = CaseModel.objects.filter(id=id)
            qs.update(**data)
            for obj in qs:
                record(request, 13, obj)
                obj.save()
            return Json_Response(msg='修改成功')
        else:
            return Form_Invalid(form)

    @permission_verify(40002)
    def delete(self, request):
        form = CaseForm.Delete(request)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            for obj in CaseModel.objects.filter(id=id):
                obj_copy = deepcopy(obj)
                obj.delete()
                record(request, 12, obj_copy)
            return Json_Response(msg='删除成功')
        else:
            return Form_Invalid(form)

    @permission_verify(40001)
    def list(self, request):
        form = CaseForm.List(request)
        if form.is_valid():
            result = []
            data = form.cleaned_data
            page, page_size = data.pop('page'), data.pop('page_size')
            qs = CaseModel.objects.filter()
            total = qs.count()
            for obj in paginate(qs, page, page_size).values_list(
                    'id', 'name', 'protocol', 'method', 'url', 'project__id', 'project__proj_name', 'desc',
                    named=True):
                result.append({
                    'id': obj.id,
                    'name': obj.name,
                    'protocol': obj.protocol,
                    'method': obj.method,
                    'url': obj.url,
                    'project': {
                        'id': obj.project__id,
                        'name': obj.project__proj_name
                    },
                    'desc': obj.desc
                })
            return Json_Response(msg='查询成功', data={
                'page': page,
                'page_size': page_size,
                'total': total,
                'result': result
            })
        else:
            return Form_Invalid(form)

    @permission_verify(40001)
    def case_detail(self, request):
        form = CaseForm.Detail(request)
        if form.is_valid():
            result = {}
            data = form.cleaned_data
            id = data.pop('id')
            for obj in CaseModel.objects.filter(id=id).values_list(
                    'id', 'name', 'desc', 'server', 'protocol', 'url', 'method',
                    'headers',
                    'param_data', 'form_data', 'json_data',
                    'assert_status', 'assert_json', 'assert_headers',
                    'project__id', 'project__proj_name', 'redirect',
                    named=True
            ):
                result = {
                    'id': obj.id,
                    'name': obj.name,
                    'desc': obj.desc,
                    'server': obj.server,
                    'protocol': obj.protocol,
                    'url': obj.url,
                    'method': obj.method,
                    'headers': obj.headers,
                    'param_data': obj.param_data,
                    'form_data': obj.form_data,
                    'json_data': obj.json_data,
                    'assert_status': obj.assert_status,
                    'assert_json': obj.assert_json,
                    'assert_headers': obj.assert_headers,
                    'project': {
                        'id': obj.project__id,
                        'name': obj.project__proj_name
                    },
                    'redirect': obj.redirect
                }
            return Json_Response(msg='查询成功', data=result)
        else:
            return Form_Invalid(form)

    @permission_verify(40002)
    def copy(self, request):
        form = CaseForm.Copy(request)
        if form.is_valid():
            data = form.cleaned_data
            id = data.pop('id')
            for obj in CaseModel.objects.filter(id=id).values():
                new_obj = deepcopy(obj)
                new_obj['name'] = obj['name'] + '_copy{}'.format(time.time())
                del new_obj['id']
                CaseModel.objects.create(**new_obj)
            return Json_Response(msg='复制成功')
        else:
            return Form_Invalid(form)
